// 共享音乐播放数据状态
import { HYEventStore } from "hy-event-store"
import { getSongDetail, getSongLyric } from "../service/api_player"
import { getSongUrl } from "../service/api_user"
import parseLyric from '../utils/parse-lyric'
// 创建播放器
// const audioContext = wx.createInnerAudioContext()   // 前台播放
const audioContext = wx.getBackgroundAudioManager()   // 背景播放
const playerStore = new HYEventStore({
  state: {
    isStop: false,   // 是否 关闭音乐
    // 属性
    id: "",    // 歌曲id
    songInfo: {},  // 歌曲信息
    songLyric: [],  // 歌词信息
    durationTime: '',    // 歌曲总时长
    url: "",      // 播放链接

    currentTime: '',  // 记录当前播放时间
    currentIndex: 0,  // 记录当前歌词位置
    currentLyricText: "",  // 当前歌词

    playModeIdex: 0,   // 播放模式
    isPlaying: false,   // 是否播放

    playListSongs: [],   // 播放的歌单
    playListIndex: 0,    // 歌曲所在歌单的位置
  },
  actions: {
    // 获取歌曲数据
    async playMusicIdInfoAction(ctx, { id, isRefresh = false }) {
      if (ctx.id === id && !isRefresh) return // 防止重复播放

      // 清除之前的数据
      ctx.songInfo = {}
      ctx.songLyric = []
      ctx.durationTime = ''
      ctx.currentTime = ''
      ctx.currentIndex = 0
      ctx.currentLyricText = ""
      ctx.id = id
      ctx.isPlaying = true   // 开始播放
      // 请求歌曲信息
      getSongDetail(id).then(res => {
        ctx.songInfo = res.data.songs[0]
        ctx.durationTime = res.data.songs[0].dt
        audioContext.title = res.data.songs[0].name
      })
      // 请求歌词并重组
      getSongLyric(id).then(res => {
        if (res.data.lrc.lyric != undefined) {
          const songLyric = parseLyric(res.data.lrc.lyric)
          ctx.songLyric = songLyric
        } else {
          ctx.songLyric = []
        }
      })
      // audioContext 使用全局播放器 播放音乐
      audioContext.stop()
      // 获取播放链接
      const res = await getSongUrl(id)
      ctx.url = res.data.data[0].url
      console.log(ctx.url);
      audioContext.src = ctx.url
      audioContext.title = id
      audioContext.autoplay = true    // 自动播放

      this.dispatch("setupAudioTextListenerAction")
    },
    // 监听歌曲播放 修改数据
    setupAudioTextListenerAction(ctx) {
      audioContext.onCanplay(() => {   // 全局配置 当数据流准备好再播放 防止autoplay出问题
        audioContext.play()
      })
      // 随着播放时间触发的函数
      audioContext.onTimeUpdate(() => {
        const currentTime = audioContext.currentTime * 1000 // 毫秒
        ctx.currentTime = currentTime
        // 根据时间获取歌词
        if (!ctx.songLyric) {
          console.log("歌词错误");
          return
        }
        let i = 0
        for (; i < ctx.songLyric.length; i++) {
          const currentLyric = ctx.songLyric[i]
          if (currentTime <= currentLyric.time) break
        }
        let currentIndex = i - 1
        if (currentIndex != ctx.currentIndex) {
          ctx.currentIndex = currentIndex
          try {
            if (ctx.songLyric[currentIndex].text == undefined) {
              ctx.currentLyricText = ""
              console.log("1!!!!!!");
            } else {
              ctx.currentLyricText = ctx.songLyric[currentIndex].text
            }
          } catch (error) {
            console.log("该时间没有歌词");
          }
        }
      })
      // 当歌曲播放结束
      audioContext.onEnded(() => {
        this.dispatch("changeNewMusicAction", "next")
      })
      // 监听播放和暂停
      audioContext.onPause(() => {
        ctx.isPlaying = false
      })
      audioContext.onPlay(() => {
        ctx.isPlaying = true
      })
      // 监听 关闭事件 会清空 scr title等数据
      audioContext.onStop(() => {
        ctx.isPlaying = false
        ctx.isStop = true
      })
    },
    // 是否播放
    changeMusicIsPlayingAction(ctx) {
      ctx.isPlaying = !ctx.isPlaying
      if (ctx.isPlaying && ctx.isStop) {
        audioContext.src = ctx.url
        if (ctx.currentSong.name) {
          audioContext.title = ctx.currentSong.name
        } else {
        }
        ctx.isStop = false
      }
      ctx.isPlaying ? audioContext.play() : audioContext.pause()
    },
    // 上一首/下一首 播放
    changeNewMusicAction(ctx, direction) {
      switch (ctx.playModeIdex) {
        case 0:  // 顺序播放
          if (direction == "next") {  // 下一曲
            if (ctx.playListIndex == ctx.playListSongs.length - 1) {
              ctx.playListIndex = 0
            } else {
              ctx.playListIndex = ctx.playListIndex + 1
            }
          } else if (direction == "prev") { // 上一曲
            if (ctx.playListIndex == 0) {
              ctx.playListIndex = ctx.playListSongs.length - 1
            } else {
              ctx.playListIndex = ctx.playListIndex - 1
            }
          }
          break;
        case 1:   // 循环播放
          break;
        case 2:   // 随机播放
          const randomIndex = Math.floor(Math.random() * ctx.playListSongs.length)
          if (ctx.playListIndex == randomIndex) {  // 防止随机到同个歌曲
            ctx.playListIndex = Math.floor(Math.random() * ctx.playListSongs.length)
          } else {
            ctx.playListIndex = randomIndex
          }
          console.log(ctx.playListIndex);

          break;
      }
      let currentSong = ctx.playListSongs[ctx.playListIndex]
      if (!currentSong) {
        currentSong = ctx.songInfo
      }
      console.log(this);
      this.dispatch("playMusicIdInfoAction", { id: currentSong.id, isRefresh: true })
    }
  }
})

export { audioContext, playerStore }
